package sunwin.yoms.web.controller.publicty;

import jodd.datetime.JDateTime;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sunwin.yoms.comm.FileHelper;
import sunwin.yoms.comm.YomsException;
import sunwin.yoms.comm.YomsFunction;
import sunwin.yoms.comm.YomsPage;
import sunwin.yoms.domain.publicty.NewsDomain;
import sunwin.yoms.service.comm.YomsDefaultData;
import sunwin.yoms.service.publicty.NewsService;
import sunwin.yoms.web.comm.*;
import sunwin.yoms.web.comm.resolverArg.YomsArrayParam;
import sunwin.yoms.web.comm.resolverArg.YomsDateParam;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by watson on 2015/7/27.
 */
@Controller
public class NewsController {
    @Autowired
    private NewsService newsService;
    @Autowired
    private YomsControllerDefaultData defaultData;

    private final String FindNvm = "publicty/news.find";
    private final String CreateNvm = "publicty/news.create";
    private final String EditNvm = "publicty/news.edit";
    private final String DeleteNvm = "publicty/delete.find";

    /**
     * 查找新闻
     *
     * @param news
     * @param pageIndex
     * @param startTime
     * @param endTime
     * @param modelMap
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.FindNews, method = RequestMethod.GET)
    @YomsController(functionNo = YomsFunction.FindNews, viewName = FindNvm)
    public ModelAndView findNews(
            NewsDomain news,
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            @YomsDateParam JDateTime startTime,
            @YomsDateParam JDateTime endTime,
            ModelMap modelMap) throws YomsException {
        modelMap.addAttribute("news", news);
        modelMap.addAttribute("startTime", startTime == null ? null : startTime.toString("YYYY-MM-DD hh:mm"));
        modelMap.addAttribute("endTime", endTime == null ? null : endTime.toString("YYYY-MM-DD hh:mm"));

        YomsPage yomsPage = new YomsPage();
        yomsPage.setPageIndex(pageIndex);
        Date date1 = startTime == null ? null : startTime.convertToDate();
        Date date2 = endTime == null ? null : endTime.convertToDate();
        List<NewsDomain> newsDomains = newsService.findNews(news, yomsPage, date1, date2);
        ModelAndView mav = new ModelAndView();
        mav.addObject("yomsPage", yomsPage);
        mav.addObject("newsList", newsDomains);
        return mav;
    }


    /**
     * 访问创建新闻页面
     */
    @RequestMapping(value = R.CreateNews, method = RequestMethod.GET)
    @YomsController(viewName = CreateNvm)
    public void createNews() {
    }

    /**
     * 创建新闻
     *
     * @param newsDomain
     * @param date1
     * @param date2
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.CreateNews, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.CreateNews, viewName = CreateNvm, isAjax = true)
    @ResponseBody
    public YomsAjaxAnswer createNews(NewsDomain newsDomain,
                                     @YomsDateParam JDateTime date1,
                                     @YomsDateParam JDateTime date2) throws YomsException {
        String img = newsDomain.getNewsImg();
        String content = newsDomain.getNewsContent();
        newsDomain.setNewsImg("");
        newsDomain.setNewsContent("");
        if (date1 == null) {
            newsDomain.setNewsBegintime(new JDateTime().convertToDate());
        } else {
            newsDomain.setNewsBegintime(date1.convertToDate());
        }
        if (date2 == null) {
            Calendar cld = Calendar.getInstance();

            cld.setTime(newsDomain.getNewsBegintime());

            cld.add(Calendar.YEAR, +1000);
            newsDomain.setNewsEndtime(cld.getTime());
        } else {
            newsDomain.setNewsEndtime(date2.convertToDate());

        }
        newsDomain.setNewsUserId(defaultData.getCurrentYomsUserDetails().getUserid());
        newsService.createNews(newsDomain);

        newsDomain.setNewsImg(img);
        newsDomain.setNewsContent(content);
        editNews(newsDomain, date1, date2);

        YomsAjaxAnswer yomsAjaxAnswer = new YomsAjaxAnswer();
        yomsAjaxAnswer.setSuccess(true);
        return yomsAjaxAnswer;
    }

    /**
     * 访问编辑用户编辑
     *
     * @param id
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.EditNews, method = RequestMethod.GET)
    @YomsController(functionNo = YomsFunction.EditNews, viewName = EditNvm)
    public ModelAndView editNews(@RequestParam(required = false, defaultValue = "-1") int id) throws YomsException {
        NewsDomain newsDomain = newsService.getNewsById(id);
        ModelAndView mav = new ModelAndView();
        mav.addObject("news", newsDomain);
        return mav;
    }

    /**
     * 编辑新闻
     *
     * @param newsDomain
     * @param date1
     * @param date2
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.EditNews, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.EditNews, viewName = EditNvm)
    @ResponseBody
    public YomsAjaxAnswer editNews(NewsDomain newsDomain,
                                   @YomsDateParam JDateTime date1,
                                   @YomsDateParam JDateTime date2) throws YomsException {

        recompileImg(newsDomain);

        if (date1 == null) {
            newsDomain.setNewsBegintime(new JDateTime(System.currentTimeMillis()).convertToDate());
        } else {
            newsDomain.setNewsBegintime(date1.convertToDate());
        }
        if (date2 == null) {
            Calendar cld = Calendar.getInstance();

            cld.setTime(newsDomain.getNewsBegintime());

            cld.add(Calendar.YEAR, +1000);
            newsDomain.setNewsEndtime(cld.getTime());
        } else {
            newsDomain.setNewsEndtime(date2.convertToDate());

        }
        newsService.updateNews(newsDomain);
        YomsAjaxAnswer yomsAjaxAnswer = new YomsAjaxAnswer();
        yomsAjaxAnswer.setSuccess(true);
        return yomsAjaxAnswer;
    }

    /**
     * 删除新闻
     *
     * @param ids
     * @return
     * @throws YomsException
     */
    @RequestMapping(value = R.DelNews, method = RequestMethod.POST)
    @YomsController(functionNo = YomsFunction.DelNews)
    @ResponseBody
    public YomsAjaxAnswer delNews(@YomsArrayParam List<Integer> ids) throws YomsException {
        if (ids != null) {
            for (int id : ids) {
                newsService.delNews(id);

                delNewsImages(id, "content");
                delNewsImages(id, "thumbnail");
            }
        }
        YomsAjaxAnswer yomsAjaxAnswer = new YomsAjaxAnswer();
        yomsAjaxAnswer.setSuccess(true);
        return yomsAjaxAnswer;
    }

    /**
     * 删除新闻相关的图片资源
     *
     * @param id
     * @param folder
     */
    private void delNewsImages(int id, String folder) {
        //获取图片路径
        File file = new File(YomsDefaultData.WebRoot, String.format("img/news/%s/%s", folder, id));
        //判断图片资源文件夹是否存在
        if (file.exists()) {
            String imgPath = file.getAbsolutePath();
            FileHelper.delFolder(imgPath);
        }
    }

    /**
     * 重新编译图片
     *
     * @param newsDomain
     */
    private void recompileImg(NewsDomain newsDomain) {
        if (newsDomain.getNewsContent() != null) {
            newsDomain.setNewsContent(YomsBase64Image.recompileImgSrc(
                    newsDomain.getNewsContent(),
                    newsDomain.getNewsId(), "news/content").getValue());
        } else {
            newsDomain.setNewsContent("");
        }

        String img = YomsBase64Image.restoreBase64code(newsDomain.getNewsImg());
        if (newsDomain.getNewsImg() != null &&
                !newsDomain.getNewsImg().contains("default/default-news.png")) {
            String value = YomsBase64Image.recompileImgSrc(img, newsDomain.getNewsId(), "news/thumbnail").getValue();

            String imgPage = YomsDefaultData.WebRoot + YomsBase64Image.getSrcValue(value);
            try {
                Thumbnails.of(imgPage).size(570, 320).toFile(imgPage);
            } catch (IOException e) {
                e.printStackTrace();
            }

            newsDomain.setNewsImg(YomsBase64Image.getSrcValue(value));
        } else {
            newsDomain.setNewsImg("");
        }
    }
}
